package institution

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func FindOneVehicle(ctx context.Context, filter *bson.D, opts ...*options.FindOneOptions) (*Vehicle, error) {
	result := new(Vehicle)
	err := result.GetCollection().FindOne(ctx, filter, opts...).Decode(result)
	if err != nil {
		return nil, err
	}
	return result, err
}

func decodeVehicleCursor(ctx context.Context, cursor *mongo.Cursor) (VehicleList *[]Vehicle, err error) {
	list := make([]Vehicle, 0)
	err = cursor.All(ctx, VehicleList)
	if err != nil {
		return nil, err
	}
	return &list, err
}

func QueryManyVehicle(ctx context.Context, filter interface{}, opts ...*options.FindOptions) (result *[]Vehicle, err error) {
	cursor, err := (&Vehicle{}).GetCollection().Find(ctx, filter, opts...)
	if err != nil {
		return nil, err
	}
	result, err = decodeVehicleCursor(ctx, cursor)
	return result, err
}

// FindLastOne /* 查找单个 */
func (v *Vehicle) FindLastOne(ctx context.Context, filter *bson.D, opts ...*options.FindOneOptions) error {
	_opt := make([]*options.FindOneOptions, 0)
	for _, opt := range opts {
		_opt = append(_opt, opt)
	}
	_opt = append(_opt, options.FindOne().SetSort(bson.D{{"_id", -1}}))
	return v.GetCollection().FindOne(ctx, *filter, _opt...).Decode(v)
}

func (v *Vehicle) FindByID(ctx context.Context, id any, opts ...*options.FindOneOptions) error {
	return v.FindLastOne(ctx, &bson.D{{"_id", id}}, opts...)
}

type VehicleList []Vehicle

// FindMany /* 查找d多个 */
func (vs *VehicleList) FindMany(ctx context.Context, filter *bson.D, opts ...*options.FindOptions) error {
	_opt := make([]*options.FindOptions, 0)
	_opt = append(_opt, options.Find().SetSort(bson.D{{"_id", -1}}))
	for _, opt := range opts {
		_opt = append(_opt, opt)
	}
	cursor, err := (&Vehicle{}).GetCollection().Find(ctx, *filter, _opt...)
	if err != nil {
		return err
	}
	return cursor.All(ctx, vs)
}
